package com.wing.qualityTesting.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.enums.MaintenanceEnum;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.CodeUtil;
import com.wing.common.utils.UniqueIdGeneratorUtil;
import com.wing.productionPlan.dao.DynamicDao;
import com.wing.productionPlan.model.entity.ProductionTheWorkOrder;
import com.wing.productionPlan.model.entity.ProductionWorkOrder;
import com.wing.productionPlan.model.entity.QualityTestingRecordDetail;
import com.wing.productionPlan.service.ProductionPieceRateDetailService;
import com.wing.productionPlan.service.ProductionTheWorkOrderService;
import com.wing.productionPlan.service.ProductionWorkOrderService;
import com.wing.productionPlan.service.QualityTestingRecordDetailService;
import com.wing.qualityTesting.dao.WorkOrderQualityTestingTaskDao;
import com.wing.qualityTesting.model.entity.QualityTestingRecord;
import com.wing.qualityTesting.model.entity.WorkOrderQualityTestingTask;
import com.wing.qualityTesting.model.request.WorkOrderQualityTestingTaskForm;
import com.wing.qualityTesting.model.response.WorkOrderQualityTestingTaskNeedVo;
import com.wing.qualityTesting.model.response.WorkOrderQualityTestingTaskVO;
import com.wing.utils.KuaiMaiPrintUtils;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.ThemeResolver;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.wing.productionPlan.model.entity.ProductionTheWorkOrder.Status.sendOver;
import static com.wing.qualityTesting.model.entity.WorkOrderQualityTestingTask.Status.inspect;

/**
 * 开工单质检任务表-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class WorkOrderQualityTestingTaskServiceImpl extends ServiceImpl<WorkOrderQualityTestingTaskDao, WorkOrderQualityTestingTask> implements WorkOrderQualityTestingTaskService {
    @Autowired
    private DynamicDao dynamicDao;
    @Autowired
    private ProductionTheWorkOrderService productionTheWorkOrderService;

    @Autowired
    private QualityTestingRecordValueService qualityTestingRecordValueService;

    @Autowired
    private QualityTestingRecordService qualityTestingRecordService;


    @Autowired
    private QualityTestingRecordDetailService qualityTestingRecordDetailService;

    @Autowired
    private ProductionWorkOrderService productionWorkOrderService;

    @Autowired
    private ThemeResolver themeResolver;

    @Autowired
    private ProductionPieceRateDetailService productionPieceRateDetailService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int add(WorkOrderQualityTestingTaskForm workOrderQualityTestingTaskForm, String status) {
        String qualityAttributes = this.productionWorkOrderService.getQualityAttributes(workOrderQualityTestingTaskForm.getWorkOrderId());
        //如果是一物一检 判断报工数 是否大于剩余报工数
        if(StrUtil.isNotBlank(qualityAttributes) && MaintenanceEnum.qualityNatureEmum.YWYJ.getCode().equals(qualityAttributes)){
            ProductionTheWorkOrder byId = this.productionTheWorkOrderService.getById(workOrderQualityTestingTaskForm.getReportOrderId());
            int qualityQuantity = byId.getQualityQuantity() ==null?0:byId.getQualityQuantity();
            if (qualityQuantity + workOrderQualityTestingTaskForm.getSubmissionQuantity() > byId.getWorkQuantity()){
                return 2;
            }
        }
        //校验
        WorkOrderQualityTestingTask workOrderQualityTestingTask = new WorkOrderQualityTestingTask();

        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(WorkOrderQualityTestingTask.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(workOrderQualityTestingTaskForm, workOrderQualityTestingTask, copyOptions);
        String today = DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN);
        Integer maxNo = dynamicDao.getDayMaxNo("ord_work_order_quality_testing_task");
        String no = CodeUtil.getCode(maxNo);
        workOrderQualityTestingTask.setCreator(JwtUtils.getLoginUserId());
        workOrderQualityTestingTask.setCreatorName(JwtUtils.getLoginUsername());
        workOrderQualityTestingTask.setEnterpriseCode(JwtUtils.getEnterpriseCode());
        workOrderQualityTestingTask.setNo(Integer.valueOf(no));
        workOrderQualityTestingTask.setReportOrderId(workOrderQualityTestingTaskForm.getReportOrderId());
        workOrderQualityTestingTask.setDay(Integer.valueOf(today));
        //重新生产code
        String taskCode = UniqueIdGeneratorUtil.generateUniqueId("GD", "yyyyMMdd", 1000, 9999);
        workOrderQualityTestingTask.setCode(taskCode);
        workOrderQualityTestingTask.setStatus(WorkOrderQualityTestingTask.Status.confirm);
        workOrderQualityTestingTask.setSubmitPostId(JwtUtils.getPostId());
        workOrderQualityTestingTask.setSubmitDepId(JwtUtils.getDepartmentId());
        //非首件检测
        workOrderQualityTestingTask.setFirstCheckStatus(status);
        save(workOrderQualityTestingTask);

        //添加记录
        QualityTestingRecord record = new QualityTestingRecord();
        Integer maxNoRecord = dynamicDao.getDayMaxNo("ord_quality_testing_record");
        String codeRecord = CodeUtil.getCode(maxNoRecord);
        record.setCode(UniqueIdGeneratorUtil.generateUniqueId("ZJ", "yyyyMMdd", 1000, 9999));
        record.setNo(Integer.valueOf(codeRecord));
        String todayRecord = DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN);
        record.setDay(Integer.valueOf(todayRecord));
        record.setQualityTestingTaskId(workOrderQualityTestingTask.getId());
        record.setRemark("自动生成记录");
        record.setCreatorName(JwtUtils.getLoginUsername());
        record.setCreator(JwtUtils.getLoginUserId());
        record.setInspectDeviceCode(workOrderQualityTestingTask.getInspectDeviceCode());
        record.setCreateTime(LocalDateTime.now());
        record.setEnterpriseCode(JwtUtils.getEnterpriseCode());
        record.setWorkOrderId(workOrderQualityTestingTaskForm.getWorkOrderId());
        boolean save = this.qualityTestingRecordService.save(record);

        if (save) {
            //查询他是否简易检测(一物一检)
            if (StrUtil.isNotBlank(qualityAttributes) && MaintenanceEnum.qualityNatureEmum.YWYJ.getCode().equals(qualityAttributes)) {
                //设置检测样品
                if (workOrderQualityTestingTaskForm.getSubmissionQuantity() != null) {
                    List<QualityTestingRecordDetail> details = new ArrayList<>();
                    for (int i = 1; i <= workOrderQualityTestingTaskForm.getSubmissionQuantity(); i++) {
                        QualityTestingRecordDetail detail = new QualityTestingRecordDetail();
                        Integer maxNoDt = dynamicDao.getDayMaxNo("ord_quality_testing_record_detail");
                        String codeDt = CodeUtil.getCode(maxNoDt);
                        detail.setCode(UniqueIdGeneratorUtil.generateUniqueId("ZJD", "yyyyMMdd", 100, 999));
                        detail.setNo(Integer.valueOf(codeDt));
                        String todayDt = DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN);
                        detail.setDay(Integer.valueOf(todayDt));
                        detail.setCreatorName(JwtUtils.getLoginUsername());
                        detail.setCreator(JwtUtils.getLoginUserId());
                        detail.setCreateTime(LocalDateTime.now());
                        detail.setSampleCode(workOrderQualityTestingTask.getCode() + "-" + i);
                        detail.setQualityTestingRecordId(record.getId());
                        detail.setQualityTestingTaskId(workOrderQualityTestingTask.getId());
                        detail.setInspectDeviceCode("");
                        detail.setProcessId(workOrderQualityTestingTaskForm.getProcessId());
                        detail.setRemark("");
                        detail.setProcessName(workOrderQualityTestingTaskForm.getProcessName());
                        detail.setStatus("1");
                        details.add(detail);
                    }
                    boolean saveBatch = this.qualityTestingRecordDetailService.saveBatch(details);
                    if (saveBatch) {
                        return 1;
                    }
                }
            } else {
                //简易检测 设置一个样品
                QualityTestingRecordDetail detail = new QualityTestingRecordDetail();
                Integer maxNoDt = dynamicDao.getDayMaxNo("ord_quality_testing_record_detail");
                String codeDt = CodeUtil.getCode(maxNoDt);
                detail.setCode(UniqueIdGeneratorUtil.generateUniqueId("ZJD", "yyyyMMdd", 100, 999));
                detail.setNo(Integer.valueOf(codeDt));
                String todayDt = DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN);
                detail.setDay(Integer.valueOf(todayDt));
                detail.setCreatorName(JwtUtils.getLoginUsername());
                detail.setCreator(JwtUtils.getLoginUserId());
                detail.setCreateTime(LocalDateTime.now());
                //简易检测
                detail.setSampleCode(workOrderQualityTestingTask.getCode() + "-" + "SIMP");
                detail.setQualityTestingRecordId(record.getId());
                detail.setQualityTestingTaskId(workOrderQualityTestingTask.getId());
                detail.setInspectDeviceCode("");
                detail.setProcessId(workOrderQualityTestingTaskForm.getProcessId());
                detail.setRemark("");
                detail.setProcessName(workOrderQualityTestingTaskForm.getProcessName());
                detail.setStatus("1");
                this.qualityTestingRecordDetailService.save(detail);
                return 1;
            }
        }
        return 0;
    }

    @Override
    public List<WorkOrderQualityTestingTaskVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<WorkOrderQualityTestingTaskVO> pageList4app(Page page, Map<String, Object> params) {
        List<WorkOrderQualityTestingTaskVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public WorkOrderQualityTestingTaskVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Override
    public void printLabels(Long id) throws Exception {
        WorkOrderQualityTestingTaskVO testingTaskVO = baseMapper.get4appById(id);
        if (testingTaskVO == null) {
            throw new BusinessException("质检任务不存在！");
        }
        JSONArray renderDataJsonArray = new JSONArray();
        for (int i = 0; i < testingTaskVO.getSubmissionQuantity(); i++) {
           /* String printCode = null;
            printCode = testingTaskVO.getCode() + "-" + (i +1);
            JsonResult<String> barCode = enterpriseClient.getBarCode(printCode);
            String filePath = PrintUtil.uploadPhoto(printCode, barCode.getData(), ".jpg");
            File file = new File(filePath);
            PrintUtil.JPGPrint(file,"HPRT N51");*/
            //file.delete();
            //云打印
            JSONObject renderDataJson = new JSONObject();
            JSONArray jsonArray = new JSONArray();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("skuCode", "");
            jsonObject.put("qrCode", testingTaskVO.getCode() + "-" + (i + 1));
            jsonArray.add(jsonObject);
            renderDataJson.put("table_test", jsonArray);
            renderDataJsonArray.add(renderDataJson);
        }
        KuaiMaiPrintUtils.barCodePrint(renderDataJsonArray);
    }

    @Override
    public WorkOrderQualityTestingTaskNeedVo getNeedInfoBy(Long qualityTestingTaskId) {
        return qualityTestingRecordValueService.getNeedInfoBy(qualityTestingTaskId);
    }

    /**
     * 查询真正的抽检数
     *
     * @param id
     * @return
     */
    @Override
    public int selectCJCount(Long id) {
        return baseMapper.selectCJCount(id);
    }

    /**
     * 查询真正的抽检数
     *
     * @param id
     * @return
     */
    @Override
    public int selectHGCount(Long id) {
        return baseMapper.selectHGCount(id);
    }

    /**
     * 修改质检任务
     *
     * @param workOrderQualityTestingTask 任务实体
     * @return
     */
    @Override
    @Transactional
    public int updateInfoById(WorkOrderQualityTestingTask workOrderQualityTestingTask) {
        ProductionWorkOrder byId = this.productionWorkOrderService.getById(workOrderQualityTestingTask.getWorkOrderId());
        if (byId.getCanGetQuantity() <= 0 || byId.getCanGetQuantity() < workOrderQualityTestingTask.getSubmissionQuantity()) {
            return 2;
        }
        workOrderQualityTestingTask.setStatus(inspect);
        boolean b = updateById(workOrderQualityTestingTask);
        if (b) {
            Long id = workOrderQualityTestingTask.getId();
            QueryWrapper<QualityTestingRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("quality_testing_task_id", id);
            QualityTestingRecord one = this.qualityTestingRecordService.getOne(queryWrapper);
            one.setUpdateTime(LocalDateTime.now());
            one.setModifier(JwtUtils.getLoginUserId());
            one.setModifierName(JwtUtils.getLoginUsername());
            one.setGetDepId(JwtUtils.getDepartmentId());
            one.setGetPostId(JwtUtils.getPostId());
            boolean updateById = this.qualityTestingRecordService.updateById(one);
            if (updateById) {
                //修改报工单送检数
                ProductionTheWorkOrder rep = productionTheWorkOrderService.getById(workOrderQualityTestingTask.getReportOrderId());
                rep.setUpdateTime(LocalDateTime.now());
                rep.setModifier(JwtUtils.getLoginUserId());
                rep.setModifierName(JwtUtils.getLoginUsername());
                //判断当前开工单是否是一物一检
                String qualityAttributes = this.productionWorkOrderService.getQualityAttributes(workOrderQualityTestingTask.getWorkOrderId());
                //如果是一物一检 判断报工数 是否大于剩余报工数
                int qualityQuantity = rep.getQualityQuantity() == null?0:rep.getQualityQuantity();
                if(StrUtil.isNotBlank(qualityAttributes) && MaintenanceEnum.qualityNatureEmum.YWYJ.getCode().equals(qualityAttributes)){
                    if (qualityQuantity + workOrderQualityTestingTask.getSubmissionQuantity() >= rep.getWorkQuantity()){
                        //这个报工单 送检完成
                        rep.setStatus(sendOver);
                    }
                }
                //简易质检或者其他的也判定为送检完成
                else{
                    rep.setStatus(sendOver);
                }
                rep.setQualityQuantity(qualityQuantity+workOrderQualityTestingTask.getSubmissionQuantity());
                this.productionTheWorkOrderService.updateById(rep);

                /*if (sendOver.equals(rep.getStatus())) {
                    //生成计件工资明细
                    productionPieceRateDetailService.create(rep, byId);
                }*/

                if (ObjectUtil.isNotEmpty(byId)) {
                    //可认领数
                    byId.setCanGetQuantity(byId.getCanGetQuantity() - workOrderQualityTestingTask.getSubmissionQuantity());
                    byId.setModifier(JwtUtils.getLoginUserId());
                    //设置报工数
//                    Integer reportedQuality = byId.getReportedQuantity() == null?0:byId.getReportedQuantity();
//                    byId.setReportedQuantity(reportedQuality + workOrderQualityTestingTask.getSubmissionQuantity());
                    byId.setModifierName(JwtUtils.getLoginUsername());
                    byId.setUpdateTime(LocalDateTime.now());
                    boolean updated = this.productionWorkOrderService.updateById(byId);
                    if (updated){
                        return 1;
                    }
                }
            }
        }
        return 0;
    }
}
